#include "CGlobals.h"
#include "CEventReceiver.h"
#include "CUserInterface.h"
#include "CLevelEditor.h"
#include "ISceneManager.h"
#include "ISceneNode.h"
#include "IControl.h"
#include "CFaceControl.h"

extern CUserInterface* ui;
extern CLevelEditor* editor;

CEventReceiver::CEventReceiver()
{		
	for (u32 i=0; i<KEY_KEY_CODES_COUNT; ++i)
		KeyIsDown[i] = false;
	m_grabbed = 0;
}

bool CEventReceiver::OnEvent(const SEvent& event)
{
	if (m_grabbed)
	{
		return m_grabbed->OnEvent(event);
	}

	for (u32 i = 0; i < m_controls.size(); ++i)
	{
		if (m_controls[i]->OnEvent(event))
			return true;
	}

	if (event.EventType == EET_MOUSE_INPUT_EVENT && event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP)
	{
		if (editor->isPointOverGUI(position2di(event.MouseInput.X, event.MouseInput.Y)))
		{
			// pass it to the scene manager because the gui swallows it up :(
			g->sceneManager->postEventFromUser(event);
		}
	}

	if (event.EventType == EET_GUI_EVENT)
	{
		if (ui->receiveEvent(event))
			return true;		
	}
	if (ui->m_CinematicEditor.receiveEvent(event))
			return true;

	if (ui->m_CinematicAdjust.receiveEvent(event))
			return true;

	if (event.EventType == irr::EET_KEY_INPUT_EVENT)
	{
		KeyIsDown[event.KeyInput.Key] = event.KeyInput.PressedDown;
		
		//ms if cinematic editor is active stop procesing the event	
	}

	if (editor->receiveEvent(event))
		return true;

	return false;
}

void CEventReceiver::GrabAllEvents (IControl* control)
{
	m_grabbed = control;
}

void CEventReceiver::ReleaseGrab (IControl* control)
{
	if (m_grabbed == control)
		m_grabbed = 0;
}

void CEventReceiver::AddControl (IControl* control)
{
	m_controls.push_back(control);
}

void CEventReceiver::RemoveControl (IControl* control)
{
	ReleaseGrab(control);
	int index = m_controls.linear_search(control);
	if (index >= 0)
	{
		delete m_controls[index];
		m_controls.erase(index);
	}
}

void CEventReceiver::RemoveAllControls ()
{
	m_grabbed = 0;
	for (u32 i = 0; i < m_controls.size(); ++i)
	{
		delete m_controls[i];
	}
	m_controls.clear();
}

void CEventReceiver::DrawControls ()
{
	if (m_grabbed) {
		m_grabbed->draw();
		return;
	}
	for (u32 i = 0; i < m_controls.size(); ++i)
	{
		m_controls[i]->draw();
	}
}

void CEventReceiver::UpdateControls ( vector3df size)
{	
	for (u32 i = 0; i < m_controls.size(); ++i)
	{
		if (m_controls[i]->getType() == E_FACE)
		{
			( (CFaceControl*)m_controls[i] )->updateControl( size );
		}
	}
}